package example.common;

import org.apache.commons.io.IOUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author ZhangXianChao
 */
public class FileUtils {
    public static void download(String fileName, String filePath, HttpServletResponse response) {
        try {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        if (!org.apache.commons.lang.StringUtils.isBlank(fileName)){
            //设置文件路径
            File file = new File(filePath);
            if (file.exists()){
                // 设置文件头部
                response.setContentType("application/force-download");
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
                response.addHeader("Content-Length", String.valueOf(file.length()));
                byte[] buff = new byte[1024];
                BufferedInputStream bis = null;
                OutputStream os = null;
                try {
                    os = response.getOutputStream();
                    bis = new BufferedInputStream(new FileInputStream(file));
                    int i = bis.read(buff);
                    while (i != -1) {
                        os.write(buff, 0, buff.length);
                        os.flush();
                        i = bis.read(buff);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }


    public static void download(String[] pdfNames, String[] pdfPaths, HttpServletResponse response) {
        if (pdfNames.length == pdfPaths.length) {
            // 创建一个临时的ZIP文件（或直接在响应流中写入ZIP数据）
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ZipOutputStream zos = new ZipOutputStream(baos);

            try {
                for (int i = 0; i < pdfNames.length; i++) {
                    String encodedFileName =pdfNames[i];
                    System.out.println(encodedFileName);
                    File fileToAdd = new File(pdfPaths[i].trim()); // 去除可能存在的空格或换行符
                    if (fileToAdd.exists()&& fileToAdd.isFile()) {
                        ZipEntry zipEntry = new ZipEntry(encodedFileName);
//                        ZipEntry zipEntry = new ZipEntry(pdfNames[i].trim()); // 添加到ZIP中的文件名
                        zos.putNextEntry(zipEntry);

                        // 将文件内容写入ZIP条目
                        try (FileInputStream fis = new FileInputStream(fileToAdd)) {
                            byte[] bytes = new byte[1024];
                            int length;
                            while ((length = fis.read(bytes)) >= 0) {
                                zos.write(bytes, 0, length);
                            }
                        }
                        zos.closeEntry();
                    }
                }
                IOUtils.closeQuietly(zos);
                // 完成后，将ZIP数据写入HTTP响应
                byte[] zipData = baos.toByteArray();
                response.reset();
                response.addHeader("Access-Control-Allow-Origin", "*");
                response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
                response.setHeader("Content-Disposition", "attachment; filename=\"secondment.zip\"");
                response.addHeader("Content-Length", "" + zipData.length);
                response.setContentType("application/zip; charset=UTF-8");
                response.setCharacterEncoding("UTF-8");
                IOUtils.write(zipData, response.getOutputStream());
            } catch (IOException e) {
                // 处理异常
                e.printStackTrace();
            } finally {
                try {
                    if (zos != null) {
                        zos.close();
                    }
                    if (baos != null) {
                        baos.close();
                    }
                } catch (IOException e) {
                    // 关闭流时发生的异常处理
                    e.printStackTrace();
                }
            }
        }
    }
    public static void deleteFileOrDirectory(File file) {
        if (file.isDirectory()) {
            for (File subItem : Objects.requireNonNull(file.listFiles())) {
                deleteFileOrDirectory(subItem);
            }
            // 删除空目录
            file.delete();
        } else {
            // 直接删除文件
            file.delete();
        }
    }
}
